//
//  UIImage+Extension.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/23.
//

import Foundation
import UIKit

extension UIImage {

    /// base64生成图片
    static func base64StringToUIImage(base64String: String) -> UIImage? {
        let str = base64String
        if str.hasPrefix("data:image") {
            guard let base64Str = str.components(separatedBy: ",").last else { return nil }
            var imageData = Data(base64Encoded: base64Str, options: .ignoreUnknownCharacters)
            if imageData == nil {
                imageData = Data(base64Encoded: base64Str + "==", options: .ignoreUnknownCharacters)
            }

            if imageData != nil {
                return UIImage(data: imageData!)
            }

            return nil
        }
        return nil
    }

    /// 颜色生成图片
    convenience init?(color: UIColor,
                      size: CGSize = CGSize(width: 1, height: 1)) {
        let rect = CGRect(origin: .zero, size: size)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        guard let cgImage = image!.cgImage else { return nil }
        self.init(cgImage: cgImage)
    }

    /// 图片大小 b
    func imageSize() -> Double {
        guard let imageData = self.jpegData(compressionQuality: 1) else { return 0 }
        return ceil(Double(imageData.count))
    }
}
